import json


class User:
    user = None
    def __init__(self):
        with open('./config.json','r') as f:
            self.user_json = json.loads(f.read())
    @staticmethod
    def getUser():
        if User.user==None:
            User.user = User()
        return User.user

    @staticmethod
    def hasUser():
        return User.user.name() is not None

    '''
    调用此方法时要保证没有用户
    '''
    def newUser(self):
        print('还没有用户，请新建一个用户')
        while True:
            name = input('用户名：')
            if len(name)<2 or len(name)>10:
                print("名字需要在2-10个字符之间")
                continue
            else:
                self.user_json['name'] = name
                self.user_json['level'] = 0
                self.save()
                return
                
    
    def name(self):
        return self.user_json['name']
    def level(self):
        return self.user_json['level']

    def set_name(self,name):
        self.user_json['name'] = name
    def set_level(self,level):
        self.user_json['level'] = level

    def save(self):
        with open('./config.json','w') as f:
            json.dump(self.user_json,f)
            print("保存信息完毕")